<?php

namespace App\Services\UpdateUserInfo;

use Closure;
use App\Models\User;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Api\V1\Requests\FormRequest;
use App\Services\UserFromInviteCode\UserFromInviteCode;

class UpdateUserInfoRequest extends FormRequest
{
	protected User $inviter;

	public function rules(): array
	{
		return [
			// Only for binding parent, user cannot change own invite_code
			'invite_code' => ['nullable','string', 'min:10', 'max:10', 'exists:users', $this->inviteCode()],
			'name' => 'nullable|string|between:1,25',
			'avatar' => 'nullable|string',
			'signature' => 'nullable|max:50',
			'gender' => ['nullable', Rule::in(array_keys(config('site.user.genders')))],
			'birthday' => 'nullable|date',
			'alipay_user_no' => 'nullable|string|max:20',
            'is_locked' => 'nullable|boolean',
            'wx_image' => 'nullable|string',
            'alipay_real_name' => 'nullable|string',
            'alipay_number' => 'nullable|string',
            'bank_card' => 'nullable|string',
            'real_name' => 'nullable|string',
            'contact_phone' =>'nullable|string',
            'is_test'=> 'nullable|boolean',
            'has_command'=> 'nullable|boolean',
		];
	}

	public function inviteCode(): Closure
	{
		return function ($key, $value, $fail) {

			$parent = app(UserFromInviteCode::class, ['inviteCode' => $value])->get();

            if (! $parent) {
                return $fail('绑定上级不存在');
            } elseif ($this->user()->invite_code == $value) {
				return $fail('不可绑定自己为邀请人');
			} elseif ($value and $this->user()->parent) {
				return $fail('仅支持无归属会员修改邀请人');
			} elseif ($parent->id > $this->user()->id) {
                return $fail('仅支持老会员邀请新会员');
            }

            $this->attributes->add(['parent' => $parent]);

			return true;
		};
	}
}
